package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.Partner;
import com.heima.pojo.dto.PagePartnerDto;
import com.heima.pojo.dto.PartnerDTO;
import com.heima.pojo.vo.PartnerVo;
import com.heima.service.PartnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    /**
     * 新增合作商
     * @param partnerDTO
     * @return
     */
    @Override
    public Boolean savePartner(PartnerDTO partnerDTO) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDTO, partner);
        String password = partnerDTO.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        partner.setPassword(md5Password);

        Integer math = partnerMapper.insertPartner(partner);
        return math > 0;
    }

    /**
     * 搜索合作商
     * @param pagePartnerDto
     * @return
     */
    @Override
    public PageResult<Partner> searchPartner(PagePartnerDto pagePartnerDto) {
        PageHelper.startPage(pagePartnerDto.getPageIndex(), pagePartnerDto.getPageSize());
        Page<Partner> list = partnerMapper.findByName(pagePartnerDto);
        // 计算总页数
        int totalPage = (int) Math.ceil((double) list.getTotal() / pagePartnerDto.getPageSize());
        return new PageResult<>(
                pagePartnerDto.getPageIndex(),
                pagePartnerDto.getPageSize(),
                totalPage,
                list.getTotal(),
                list.getResult()
        );
    }

    /**
     * 合作商详情
     * @param id
     * @return
     */
    @Override
    public PartnerVo getPartner(Long id) {
        PartnerVo partnerVo = partnerMapper.queryPartner(id);
        return partnerVo;
    }

    /**
     * 修改合作商信息
     * @param partnerDTO
     * @return
     */
    @Override
    public Boolean updatePartner(PartnerDTO partnerDTO) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDTO, partner);
        Integer math = partnerMapper.modifyPartner(partner);
        return math > 0;
    }

    /**
     * 根据id删除合作商
     * @param id
     * @return
     */
    @Override
    public Boolean deletePartner(Integer id) {
        // 如果合作商的设备数量大于0，则不能删除
        Integer count = partnerMapper.queryVmCount(id);
        if (count > 0) {
            // 抛异常
            throw new RuntimeException("合作商设备数量大于0，不能删除");
        }
        Integer math = partnerMapper.deletePartner(id);
        return math > 0;
    }


}
